<template>
  <div class="terminal-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      :title="serverInfo?.name || '终端'"
      fixed
      placeholder
      left-arrow
      @click-left="handleBack"
      :border="false"
    >
      <template #right>
        <van-icon
          :name="connected ? 'success' : 'warning-o'"
          :color="connected ? '#07c160' : '#ee0a24'"
          size="20"
        />
      </template>
    </van-nav-bar>

    <!-- 终端区域 -->
    <div class="terminal-wrapper">
      <div ref="terminalRef" class="terminal-container"></div>
      
      <!-- 连接状态提示 -->
      <div v-if="!connected" class="connection-overlay">
        <van-loading v-if="connecting" type="spinner" size="36px">
          连接中...
        </van-loading>
        <div v-else class="connection-error">
          <van-icon name="warning-o" size="48" color="#ee0a24" />
          <p>连接失败</p>
          <van-button type="primary" size="small" @click="connect">
            重新连接
          </van-button>
        </div>
      </div>
    </div>

    <!-- 虚拟键盘工具栏 -->
    <div class="keyboard-toolbar">
      <!-- 常用命令 -->
      <div class="command-shortcuts">
        <van-button
          v-for="cmd in commonCommands"
          :key="cmd.key"
          plain
          size="small"
          type="primary"
          @click="sendCommand(cmd.value)"
        >
          {{ cmd.label }}
        </van-button>
      </div>

      <!-- 控制键 -->
      <div class="control-keys">
        <van-button plain size="small" @click="sendKey('Tab')">Tab</van-button>
        <van-button plain size="small" @click="sendKey('Ctrl+C')">Ctrl+C</van-button>
        <van-button plain size="small" @click="sendKey('Ctrl+D')">Ctrl+D</van-button>
        <van-button plain size="small" @click="sendKey('Enter')">Enter</van-button>
        <van-button plain size="small" @click="sendKey('Up')">↑</van-button>
        <van-button plain size="small" @click="sendKey('Down')">↓</van-button>
        <van-button plain size="small" @click="sendKey('Clear')">清屏</van-button>
        <van-button plain size="small" type="primary" @click="showCommandDialog = true">更多</van-button>
      </div>
    </div>

    <!-- 快捷命令弹窗 -->
    <van-popup
      v-model:show="showCommandDialog"
      round
      position="bottom"
      :style="{ height: '70%' }"
    >
      <div class="command-dialog">
        <van-nav-bar
          title="常用命令"
          left-text="关闭"
          @click-left="showCommandDialog = false"
        />
        <div class="command-categories">
          <van-tabs v-model:active="activeCategory" sticky>
            <van-tab v-for="category in commandCategories" :key="category.name" :title="category.name">
              <div class="command-list">
                <van-cell
                  v-for="cmd in category.commands"
                  :key="cmd.cmd"
                  :title="cmd.name"
                  :label="cmd.cmd"
                  is-link
                  @click="executeCommand(cmd.cmd)"
                >
                  <template #icon>
                    <van-icon :name="cmd.icon" class="command-icon" />
                  </template>
                </van-cell>
              </div>
            </van-tab>
          </van-tabs>
        </div>
      </div>
    </van-popup>

    <!-- 自定义输入弹窗 -->
    <van-popup
      v-model:show="showInputDialog"
      round
      position="bottom"
    >
      <div class="input-dialog">
        <van-field
          v-model="customInput"
          type="textarea"
          rows="3"
          placeholder="输入命令..."
          autofocus
        />
        <div class="input-actions">
          <van-button block type="primary" @click="sendCustomInput">
            发送
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'
import serverAPI from '@/api/servers'

const route = useRoute()
const router = useRouter()

// 状态
const terminalRef = ref(null)
const serverInfo = ref(null)
const connected = ref(false)
const connecting = ref(false)
const showCommandDialog = ref(false)
const showInputDialog = ref(false)
const customInput = ref('')
const activeCategory = ref(0)
const monitoring = ref({
  cpu: 0,
  memory: 0,
  disk: 0,
  network: { upload: 0, download: 0 }
})

// 终端实例
let terminal = null
let fitAddon = null
let ws = null

// 常用命令（顶部快捷栏）
const commonCommands = [
  { key: 'ls', label: 'ls', value: 'ls -la\n' },
  { key: 'pwd', label: 'pwd', value: 'pwd\n' },
  { key: 'top', label: 'top', value: 'top\n' },
  { key: 'df', label: 'df', value: 'df -h\n' }
]

// 命令分类
const commandCategories = [
  {
    name: '文件操作',
    commands: [
      { name: '列出文件', cmd: 'ls -la', icon: 'records' },
      { name: '当前目录', cmd: 'pwd', icon: 'location-o' },
      { name: '切换目录', cmd: 'cd ', icon: 'arrow' },
      { name: '创建目录', cmd: 'mkdir ', icon: 'add-o' },
      { name: '删除文件', cmd: 'rm ', icon: 'delete-o' },
      { name: '复制文件', cmd: 'cp ', icon: 'records' },
      { name: '移动文件', cmd: 'mv ', icon: 'exchange' },
      { name: '查看文件', cmd: 'cat ', icon: 'eye-o' },
      { name: '编辑文件', cmd: 'vi ', icon: 'edit' }
    ]
  },
  {
    name: '系统信息',
    commands: [
      { name: '系统进程', cmd: 'top', icon: 'chart-trending-o' },
      { name: '内存使用', cmd: 'free -h', icon: 'apps-o' },
      { name: '磁盘使用', cmd: 'df -h', icon: 'records' },
      { name: '系统信息', cmd: 'uname -a', icon: 'desktop-o' },
      { name: '在线用户', cmd: 'who', icon: 'friends-o' },
      { name: '运行时间', cmd: 'uptime', icon: 'clock-o' },
      { name: '网络连接', cmd: 'netstat -tuln', icon: 'cluster-o' }
    ]
  },
  {
    name: '进程管理',
    commands: [
      { name: '进程列表', cmd: 'ps aux', icon: 'bars' },
      { name: '查找进程', cmd: 'ps aux | grep ', icon: 'search' },
      { name: '杀死进程', cmd: 'kill ', icon: 'cross' },
      { name: '强制杀死', cmd: 'kill -9 ', icon: 'warning-o' }
    ]
  },
  {
    name: '网络工具',
    commands: [
      { name: 'Ping测试', cmd: 'ping -c 4 ', icon: 'cluster-o' },
      { name: '端口监听', cmd: 'netstat -tuln', icon: 'shield-o' },
      { name: '防火墙状态', cmd: 'ufw status', icon: 'shield-o' },
      { name: '下载文件', cmd: 'wget ', icon: 'down' }
    ]
  },
  {
    name: '服务管理',
    commands: [
      { name: '服务列表', cmd: 'systemctl list-units', icon: 'apps-o' },
      { name: '启动服务', cmd: 'systemctl start ', icon: 'play-circle-o' },
      { name: '停止服务', cmd: 'systemctl stop ', icon: 'stop-circle-o' },
      { name: '重启服务', cmd: 'systemctl restart ', icon: 'replay' },
      { name: '服务状态', cmd: 'systemctl status ', icon: 'info-o' }
    ]
  }
]

// 初始化终端
const initTerminal = () => {
  if (!terminalRef.value) return
  
  console.log('📱 初始化终端')
  
  terminal = new Terminal({
    cursorBlink: true,
    fontSize: 12,
    fontFamily: 'Menlo, Monaco, "Courier New", monospace',
    theme: {
      background: '#1e1e1e',
      foreground: '#d4d4d4',
      cursor: '#ffffff',
      black: '#000000',
      red: '#cd3131',
      green: '#0dbc79',
      yellow: '#e5e510',
      blue: '#2472c8',
      magenta: '#bc3fbc',
      cyan: '#11a8cd',
      white: '#e5e5e5',
      brightBlack: '#666666',
      brightRed: '#f14c4c',
      brightGreen: '#23d18b',
      brightYellow: '#f5f543',
      brightBlue: '#3b8eea',
      brightMagenta: '#d670d6',
      brightCyan: '#29b8db',
      brightWhite: '#ffffff'
    },
    allowTransparency: false,
    scrollback: 1000
  })
  
  fitAddon = new FitAddon()
  terminal.loadAddon(fitAddon)
  terminal.open(terminalRef.value)
  
  // 适配终端大小
  setTimeout(() => {
    fitAddon.fit()
  }, 100)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 调整终端大小
const handleResize = () => {
  if (fitAddon) {
    fitAddon.fit()
  }
}

// 连接服务器
const connect = async () => {
  try {
    connecting.value = true
    console.log('📱 连接服务器:', route.params.serverId)
    
    // 获取服务器信息
    const response = await serverAPI.getById(route.params.serverId)
    serverInfo.value = response.server
    
    // 建立WebSocket连接
    const token = localStorage.getItem('token')
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsUrl = `${wsProtocol}//${window.location.host}/ws/ssh?token=${token}&serverId=${route.params.serverId}`
    
    console.log('📱 WebSocket URL:', wsUrl)
    ws = new WebSocket(wsUrl)
    
    ws.onopen = () => {
      console.log('✅ WebSocket连接已建立')
      connecting.value = false
    }
    
    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        console.log('📩 收到消息:', message.type)
        
        switch (message.type) {
          case 'status':
            terminal.writeln(`\x1b[33m${message.message}\x1b[0m`)
            break
          
          case 'connected':
            terminal.writeln(`\x1b[32m${message.message}\x1b[0m`)
            connected.value = true
            showToast({ message: '连接成功', position: 'top' })
            // 自动开始监控
            startMonitoring()
            break
          
          case 'data':
            terminal.write(message.data)
            break
          
          case 'monitoring':
            monitoring.value = message.data
            break
          
          case 'error':
            terminal.writeln(`\x1b[31m错误: ${message.message || message.data}\x1b[0m`)
            showToast({ message: message.message, position: 'top' })
            break
          
          case 'disconnected':
            terminal.writeln(`\x1b[31m${message.message}\x1b[0m`)
            connected.value = false
            break
          
          default:
            console.warn('未知消息类型:', message.type)
        }
      } catch (error) {
        console.error('❌ 处理消息失败:', error)
      }
    }
    
    ws.onerror = (error) => {
      console.error('❌ WebSocket错误:', error)
      terminal.writeln('\x1b[31m连接失败\x1b[0m')
      connected.value = false
      connecting.value = false
      showToast({ message: '连接失败', position: 'top' })
    }
    
    ws.onclose = () => {
      console.log('🔌 WebSocket连接关闭')
      connected.value = false
      connecting.value = false
    }
    
    // 监听终端输入
    terminal.onData((data) => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'input',
          data
        }))
      }
    })
  } catch (error) {
    console.error('❌ 连接失败:', error)
    connecting.value = false
    showToast({ message: '获取服务器信息失败', position: 'top' })
  }
}

// 发送命令
const sendCommand = (cmd) => {
  if (terminal && ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'input',
      data: cmd
    }))
  }
}

// 发送控制键
const sendKey = (key) => {
  if (!terminal || !ws || ws.readyState !== WebSocket.OPEN) return
  
  let data = ''
  switch (key) {
    case 'Tab':
      data = '\t'
      break
    case 'Enter':
      data = '\n'
      break
    case 'Ctrl+C':
      data = '\x03'
      break
    case 'Ctrl+D':
      data = '\x04'
      break
    case 'Up':
      data = '\x1b[A'
      break
    case 'Down':
      data = '\x1b[B'
      break
    case 'Clear':
      terminal.clear()
      return
  }
  
  if (data) {
    ws.send(JSON.stringify({
      type: 'input',
      data
    }))
  }
}

// 执行命令
const executeCommand = (cmd) => {
  sendCommand(cmd)
  showCommandDialog.value = false
  
  // 如果命令不以换行结尾，显示输入框让用户补充
  if (!cmd.endsWith('\n')) {
    showInputDialog.value = true
    customInput.value = cmd
  }
}

// 发送自定义输入
const sendCustomInput = () => {
  if (customInput.value) {
    sendCommand(customInput.value + '\n')
    customInput.value = ''
  }
  showInputDialog.value = false
}

// 开始监控
const startMonitoring = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'start_monitor' }))
    console.log('📊 开始监控')
  }
}

// 停止监控
const stopMonitoring = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'stop_monitor' }))
  }
}

// 刷新监控数据
const refreshMonitoring = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'monitor' }))
    console.log('🔄 刷新监控数据')
  }
}

// 返回处理
const handleBack = () => {
  // 停止监控并断开连接
  stopMonitoring()
  if (ws) {
    ws.close()
  }
  router.back()
}

// 页面加载
onMounted(() => {
  console.log('📱 终端页加载')
  initTerminal()
  connect()
})

// 页面卸载
onBeforeUnmount(() => {
  console.log('📱 终端页卸载')
  
  // 停止监控
  stopMonitoring()
  
  // 清理
  if (ws) {
    ws.close()
  }
  if (terminal) {
    terminal.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.terminal-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
  overflow: hidden;
}

/* 终端区域 */
.terminal-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.terminal-container {
  width: 100%;
  height: 100%;
  padding: 8px;
}

/* 连接状态遮罩 */
.connection-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(30, 30, 30, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.connection-error {
  text-align: center;
  color: white;
}

.connection-error p {
  margin: 16px 0;
  font-size: 16px;
}

/* 虚拟键盘工具栏 */
.keyboard-toolbar {
  background: white;
  border-top: 1px solid #ebedf0;
  padding: 8px;
  max-height: 40vh;
  overflow-y: auto;
}

.command-shortcuts,
.control-keys {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.command-shortcuts:last-child,
.control-keys:last-child {
  margin-bottom: 0;
}

.keyboard-toolbar .van-button {
  flex-shrink: 0;
  font-size: 13px;
}

/* 命令对话框 */
.command-dialog {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f7f8fa;
  color: #323233;
}

.command-categories {
  flex: 1;
  color: #323233;
  overflow: hidden;
}

.command-list {
  padding-bottom: 16px;
}

.command-icon {
  margin-right: 12px;
  color: #1989fa;
}

/* 输入对话框 */
.input-dialog {
  padding: 16px;
}

.input-actions {
  margin-top: 12px;
}

/* Vant样式覆盖 */
:deep(.van-nav-bar) {
  background: #1e1e1e;
}

:deep(.van-nav-bar__title) {
  color: white;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-nav-bar__arrow) {
  color: white !important;
}

/* Xterm样式覆盖 */
:deep(.xterm) {
  height: 100%;
}

:deep(.xterm-viewport) {
  overflow-y: auto;
}
</style>

